package com.lagou.rpc.provider.util;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import static com.lagou.rpc.constant.Constant.*;

/**
 * @Description
 * @Date 2021/10/8 15:07
 * @Created by mike
 */
public class ZkUtil {

    //发令枪：阻塞作用
    private static CountDownLatch countDownLatch=new CountDownLatch(1);

    public static void saveInfo(String ip, String port){
        try {
            ZooKeeper zooKeeper = new ZooKeeper(ZOOKEEPER_ADDRESS, 5000, event -> {
                //监控连接状态：连接完成时，停止阻塞
                if(event.getState()== Watcher.Event.KeeperState.SyncConnected){
                    countDownLatch.countDown();
                }
            });
            //判断目录是否存在
            Stat exists = zooKeeper.exists(PROVIDER_PATH, false);
            if (null==exists){
                //目录为空，创建持久节点
                System.out.println("创建目录");
                zooKeeper.create(PROVIDER_PATH,"1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
            //加入数据
            String data=ip+":"+port;
            //创建临时顺序节点  1：客户端断开，数据自动删除 2：顺序节点，区分不同客户端
            String s = zooKeeper.create(PROVIDER_PATH + "/data", data.getBytes(),
                    ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
            System.out.println("s---->"+s);
        } catch (IOException | InterruptedException | KeeperException e) {
            e.printStackTrace();
        }
    }
}
